﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using GzipManagerPro.IO.Helpers;

namespace GzipManagerPro.IO
{
    partial class Archive
    {
        private const int HeaderProgressCount = 5;
        private const int CalculateFilesProgressCount = 2;

        internal int TotalProgress;
        internal int CurrentProgress;
       
        private byte[] _Password;
        [NonSerialized]
        private string _FileName;
        private string _StoryBoard;
        private Folder _RootFolder;

        public byte[] Password
        {
            get
            {
                return _Password;
            }
            set
            {
                _Password = value;
            }
        }

        public string StoryBoard
        {
            get
            {
                return _StoryBoard;
            }
            set
            {
                _StoryBoard = value;
            }
        }

        public Folder RootFolder
        {
            get
            {
                if (_RootFolder == null)
                    _RootFolder = new Folder();

                return _RootFolder;
            }
            set
            {
                _RootFolder = value;
            }
        }

        public string FileName
        {
            get
            {
                return _FileName;
            }
            set
            {
                _FileName = value;
            }
        }

        public void SetPassword(string password)
        {
            if (string.IsNullOrEmpty(password))
                throw new InvalidPasswordException();

            this.Password = MD5.Create("MD5").ComputeHash(Encoding.UTF8.GetBytes(password));
        }

        public bool IncludePassword
        {
            get
            {
                return this.Password != null && this.Password.Length > 0;
            }
        }

        internal void CheckPassword(string password)
        {
            if (!this.IncludePassword)
                return;

            if (string.IsNullOrEmpty(password))
                throw new InvalidPasswordException();

            byte[] buffer = MD5.Create("MD5").ComputeHash(Encoding.UTF8.GetBytes(password));

            if(buffer.Length != this.Password.Length)
                throw new InvalidPasswordException();

            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] != this.Password[i])
                    throw new InvalidPasswordException();
            }
        }
    }
}
